
<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="80px">
    <el-form-item label="备注" prop="name">
      <el-input v-model="dataForm.name" placeholder="名称"></el-input>
    </el-form-item>
    <el-form-item label="上传文件" prop="filePath">
      <el-upload
        ref="upload"
        class="upload-file"
        drag
        :action="upurl"
        :show-file-list="true"
        :before-upload="beforeAvatarUpload"
        :on-success="onSuccess"
        :on-remove="sourceRemove">
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将{{types[dataForm.type][0]}}文件拖到此处，或<em>点击上传</em></div>
      </el-upload>
    </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
  export default {
    data () {
      return {
        upurl: '',
        visible: false,
        dataForm: {
          id: 0,
          duration: 0,
          name: '',
          coverPath: '',
          cid: '',
          fileName: '',
          filePath: '',
          thumbPath: '',
          packageName: '',
          createUser: '',
          createTime: '',
          fileSize: '',
          checkStatus: ''
        },
        dataRule: {
          name: [
            { required: true, message: '备注不能为空', trigger: 'blur' }
          ],
          filePath: [
            { required: true, message: '请上传文件', trigger: 'blur' }
          ]
        },
        types: {
          1: ['视频', 'video/'],
          2: ['图片', 'image/'],
          3: ['文本(word,ppt,excel,pdf)', 'text/', 'officedocument', '/vnd.ms', '/msword', '/pdf'],
          4: ['音频', 'audio/'],
          5: ['动画(Flash)', 'flash'],
          6: ['APK', 'application/vnd.android.package-archive']
        }
      }
    },
    methods: {
      init (id, cid, type) {
        let self = this
        this.$nextTick(() => { // 在元素更新完成后执行 否则会获取不到对象
          this.has_upload = false
          this.dataForm.id = id || 0
          this.dataForm.type = type
          this.dataForm.cid = cid
          this.dataForm.name = ''
          this.visible = true
          let token = this.$cookie.get('token')
          console.log(this.dataForm.id)
          this.upurl = this.$http.adornUrl('/sys/upload?iconPath=material&type=' + type + '&token=' + token)
          // this.$refs['dataForm'].resetFields()
          setTimeout(function () {
            self.$refs.upload.clearFiles()
          }, 100)
          if (this.dataForm.id) {
            this.$http({
              url: this.$http.adornUrl(`/sys/material/info/${this.dataForm.id}`),
              method: 'get',
              params: this.$http.adornParams()
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.dataForm = data.material
              }
            })
          } else {
            this.dataForm.filePath = ''
            console.log('+++++++++++')
          }
        })
      },
      // 表单提交
      dataFormSubmit () {
        console.log("this.upurl====="+this.upurl)
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.$http({
              url: this.$http.adornUrl(`/sys/material/${!this.dataForm.id ? 'save' : 'update'}`),
              method: 'post',
              data: this.$http.adornData(
                this.dataForm
              )
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.visible = false
                    this.$emit('refreshDataList')
                  }
                })
              } else {
              this.$message.error(data.msg)
              }
            })
          }
        })
      },
      beforeAvatarUpload: function (file) {
        console.log(file)
        if (this.has_upload) {
          this.$message.error('已存在上传文件,请先移除')
          return false
        }
        let isIMG = false;
        if(file.type!='' && file.type!=null){
          //通过类型判断
          isIMG = this.checkType(file.type)
        }else {
          //类型为空(目前文档类型为空)  通过后缀判断
          isIMG = this.checkTypeByName(file.name)
        }
        const isLt8M = file.size / 1024 / 1024 < 1000
        if (!isLt8M) {
          this.$message.error('上传文件大小不能超过 1000MB!')
        }
        // console.log('isImg', isIMG)
        if (!isIMG) {
          this.$message.error('请选择' + this.types[this.dataForm.type][0] + '文件')
        }
        this.has_upload = isLt8M && isIMG
        return isLt8M && isIMG
      },
      onSuccess: function (response, file, fileList) {
        console.log('file', file)
        if (response.code === 0) {
          this.dataForm.width = response.width
          this.dataForm.height = response.height
          this.dataForm.fileName = file.name
          if (this.dataForm.type === 3) {
            this.dataForm.originalFile = response.url
            this.dataForm.filePath = response.convertPath
            this.dataForm.fileName = response.fileName
          } else {
            this.dataForm.filePath = response.url
          }
          this.dataForm.packageName = response.packageName
          this.dataForm.fileSize = file.size
          if (this.dataForm.type === 2) {
            let img = new window.Image()
            img.src = file.url
            this.dataForm.thumbPath = response.thumbPath
          }
        } else {
          this.$refs.upload.clearFiles()
          this.$message.error(response.msg)
          return false
        }
        if(this.dataForm.type === 4){
          this.dataForm.duration = response.videoTime
        }
        if(this.dataForm.type === 1){
          this.dataForm.duration = response.videoTime
          this.dataForm.coverPath = response.picPath
        }
      },
      sourceRemove: function (file, fileList) {
        if (fileList.length === 0) {
          this.has_upload = false
          this.dataForm.filePath = null
          this.dataForm.fileName = null
          this.dataForm.packageName = null
        }
      },
      checkType (typeStr) {
        const types = this.types[this.dataForm.type]
        console.log('types=========='+ types)
        for (let i = 1; i < types.length; i++) {
          console.log('typeStr=========='+ typeStr)
          // console.log('types[i]', types[i])
          if (typeStr.indexOf(types[i]) >= 0) {
            return true
          }
        }
        return false
      },
      checkTypeByName (typeStr) {
        //返回String对象中子字符串最后出现的位置.
        let seat=typeStr.lastIndexOf(".");
        //返回位于String对象中指定位置的子字符串并转换为小写.
        let extension=typeStr.substring(seat).toLowerCase();
        let allowed=[".xls",".xlsx",".txt",".doc",".docx",'.pptx','.ppt'];
        for(let i=0;i<allowed.length;i++){
          if(!(allowed[i]!=extension)){
            return true;
          }
        }
        return false;
      }

    }
  }
</script>
